package cn.liumouren.jzxd.utils;

import cn.hutool.core.util.StrUtil;
import cn.liumouren.jzxd.dao.PictureDao;
import cn.liumouren.jzxd.dao.TagDao;
import cn.liumouren.jzxd.dao.UserDao;
import cn.liumouren.jzxd.entity.Comment;
import cn.liumouren.jzxd.entity.Picture;
import cn.liumouren.jzxd.entity.Scene;
import cn.liumouren.jzxd.entity.User;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;

import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @auther: Freeman Liu
 * @date: 2020/11/2 08:29
 */
public class mapperUtils implements Serializable {

    /**
     * @param entity     实体类 zone,scene......
     * @param pictureDao PictureDao
     * @param <T>
     */
    public static <T> void associatePicturesAndEntity(T entity, PictureDao pictureDao) {
        try {
            Class<?> entityClazz = entity.getClass();

            //获取entityId
            Method idMethod = entityClazz.getDeclaredMethod("getId");
            String entityId = (String) idMethod.invoke(entity);

            Method getPicId = entityClazz.getDeclaredMethod("getPicId");
            String picId = (String) getPicId.invoke(entity);
            if (picId == null) {
                return;
            }
            picId = picId.trim();
            String[] picIds = picId.split(";");

            for (String id : picIds) {
                pictureDao.update(null, new UpdateWrapper<Picture>()
                        .set(StrUtil.lowerFirst(entityClazz.getSimpleName()) + "_id", entityId)
                        .eq("id", id));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * @param entities   包含 picId 列的对象的集合
     * @param pictureDao pictureDao
     * @param <T>
     */
    public static <T> List<T> getUrlsByEntity(List<T> entities, PictureDao pictureDao) {
        try {
            if (entities == null || entities.size() == 0) {
                return entities;
            }
            Class<?> clazz = entities.get(0).getClass();
            List<String> urls;
            Picture picture;
            Method method;
            String picId;
            String[] picIds;
            for (T entity : entities) {
                method = clazz.getDeclaredMethod("getPicId");
                picId = (String) method.invoke(entity);
                if (picId != null) {
                    picIds = picId.split(";");
                    urls = new ArrayList<>();
                    for (String id : picIds) {
                        picture = pictureDao.selectById(id);
                        if (picture != null) {
                            urls.add(picture.getUrl());
                        }
                    }
                    method = clazz.getDeclaredMethod("setUrls", List.class);
                    method.invoke(entity, urls);
                }
            }
            return entities;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("getUrlsByEntity出错!!!");
        }
    }

    public static <T> T getUrlsByEntity(T entity, PictureDao pictureDao) {
        try {
            Class<?> clazz = entity.getClass();
            List<String> urls;
            Picture picture;
            Method method;
            String picId;
            String[] picIds;
            method = clazz.getDeclaredMethod("getPicId");
            picId = (String) method.invoke(entity);
            if (picId != null) {
                picIds = picId.split(";");
                urls = new ArrayList<>();
                for (String id : picIds) {
                    picture = pictureDao.selectById(id);
                    if (picture != null) {
                        urls.add(picture.getUrl());
                    }
                }
                method = clazz.getDeclaredMethod("setUrls", List.class);
                method.invoke(entity, urls);
            }
            return entity;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("getUrlsByEntity出错!!!");
        }
    }

    /**
     * @param entities   包含 picId 列的对象的集合
     * @param pictureDao pictureDao
     * @param <T>
     */
    public static <T> IPage<T> getUrlsByEntity(IPage<T> entities, PictureDao pictureDao) {
        List<T> records = entities.getRecords();
        getUrlsByEntity(records, pictureDao);
        entities.setRecords(records);
        return entities;
    }

    public static <T> List<T> getUserByEntity(List<T> entities, UserDao userDao) {
        try {
            if (entities == null || entities.size() == 0) {
                return entities;
            }
            Class<?> clazz = entities.get(0).getClass();
            String userId;
            User user;
            Method method;
            for (T entity : entities) {
                method = clazz.getDeclaredMethod("getUserId");
                userId = (String) method.invoke(entity);
                if (userId != null) {
                    user = userDao.selectById(userId);
                    method = clazz.getDeclaredMethod("setUser", User.class);
                    method.invoke(entity, user);
                }
            }
            return entities;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("getUserByEntity出错!!!");
        }
    }

    public static List<Comment> getUserAndReplyUserByComments(List<Comment> comments, UserDao userDao) {
        for (Comment comment : comments) {
            String userId = comment.getUserId();
            if (!StringUtils.isEmpty(userId)) {
                comment.setUser(userDao.selectById(userId));
            }
            String replyUserId = comment.getReplyUserId();
            if (!StringUtils.isEmpty(replyUserId)) {
                comment.setReplyUser(userDao.selectById(replyUserId));
            }
        }
        return comments;
    }

    public static IPage<Comment> getUserAndReplyUserByComments(IPage<Comment> page, UserDao userDao) {
        List<Comment> records = page.getRecords();
        getUserAndReplyUserByComments(records, userDao);
        page.setRecords(records);
        return page;
    }

    public static List<Scene> getTagsByScenes(List<Scene> scenes, TagDao tagDao) {
        for (Scene scene : scenes) {
            scene.setTags(tagDao.getTagsByScenes(scene.getId()));
        }
        return scenes;
    }

    public static Scene getTagsByScene(Scene scene, TagDao tagDao) {
        scene.setTags(tagDao.getTagsByScenes(scene.getId()));
        return scene;
    }

    public static IPage<Scene> getTagsByScenes(IPage<Scene> page, TagDao tagDao) {
        List<Scene> scenes = page.getRecords();
        getTagsByScenes(scenes, tagDao);
        page.setRecords(scenes);
        return page;
    }
}
